package config.spring.boot.starter;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.utils.CloseableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ConfigListener
 *
 * @author ybtccc
 * @date 2019/2/20
 */
public class ConfigListener implements PathChildrenCacheListener {
    private static Logger logger = LoggerFactory.getLogger(ConfigListener.class);

    private CuratorFramework curatorFramework;
    private PathChildrenCache cache;
    private String path = "/config";


    public ConfigListener(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    public void start() throws Exception {
        cache = new PathChildrenCache(curatorFramework, path, true);
        cache.getListenable().addListener(this);
        cache.start();
    }

    public void stop() {
        CloseableUtils.closeQuietly(cache);
    }

    @Override
    public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
        logger.info("事件event: {}", event);
        String key = "";
        String value = "";
        if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)) {
            key = event.getData().getPath();
            key = key.substring(key.lastIndexOf("/") + 1);
            PropertyUtil.remove(key);
        } else if ((event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED))) {
            key = event.getData().getPath();
            key = key.substring(key.lastIndexOf("/") + 1);
            value = new String(event.getData().getData());
            PropertyUtil.set(key, value);
        } else if ((event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED))) {
            key = event.getData().getPath();
            key = key.substring(key.lastIndexOf("/") + 1);
            value = new String(event.getData().getData());
            PropertyUtil.set(key, value);
        }
    }
}
